package com.yilin.tms.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.reflect.TypeToken;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.JsonUtil;
import com.yilin.commons.util.MapUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.order.clearing.ClearingDetail;
import com.yilin.tms.core.entity.order.dispatch.DispatchOrder;
import com.yilin.tms.core.entity.order.dispatch.DispatchOrderNote;
import com.yilin.tms.core.entity.order.dispatch.DispatchOrderNoteDetail;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.goods.GoodsOrderNote;
import com.yilin.tms.core.entity.order.goods.GoodsOrderNoteDetail;
import com.yilin.tms.core.entity.order.payment.OrderPaymentCost;
import com.yilin.tms.core.entity.order.payment.OrderSettlementCost;
import com.yilin.tms.core.entity.order.rob.RobOrder;
import com.yilin.tms.core.entity.order.rob.RobOrderNote;
import com.yilin.tms.core.entity.order.rob.RobOrderNoteDetail;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrderNote;
import com.yilin.tms.core.entity.order.transit.TransitOrderNoteDetail;
import com.yilin.tms.core.entity.user.organize.MemberType;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.order.mapper.dispatch.DispatchOrderMapper;
import com.yilin.tms.order.mapper.dispatch.DispatchOrderNoteDetailMapper;
import com.yilin.tms.order.mapper.dispatch.DispatchOrderNoteMapper;
import com.yilin.tms.order.mapper.goods.GoodsOrderMapper;
import com.yilin.tms.order.mapper.goods.GoodsOrderNoteDetailMapper;
import com.yilin.tms.order.mapper.goods.GoodsOrderNoteMapper;
import com.yilin.tms.order.mapper.payment.OrderPaymentCostMapper;
import com.yilin.tms.order.mapper.payment.OrderSettlementCostMapper;
import com.yilin.tms.order.mapper.rob.RobOrderMapper;
import com.yilin.tms.order.mapper.rob.RobOrderNoteDetailMapper;
import com.yilin.tms.order.mapper.rob.RobOrderNoteMapper;
import com.yilin.tms.order.mapper.transit.TransitOrderMapper;
import com.yilin.tms.order.mapper.transit.TransitOrderNoteDetailMapper;
import com.yilin.tms.order.mapper.transit.TransitOrderNoteMapper;
import com.yilin.tms.order.service.clearing.IClearingService;
import com.yilin.tms.order.service.payment.IOrderPaymentCostService;
import com.yilin.tms.order.service.payment.IOrderSettlementCostService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MigrationService implements IMigrationService {

    private Logger logger = LoggerFactory.getLogger(MigrationService.class);

    @Resource
    DispatchOrderMapper dispatchOrderMapper;
    @Resource
    DispatchOrderNoteMapper dispatchOrderNoteMapper;
    @Resource
    DispatchOrderNoteDetailMapper dispatchOrderNoteDetailMapper;


    @Resource
    GoodsOrderMapper goodsOrderMapper;
    @Resource
    GoodsOrderNoteMapper goodsOrderNoteMapper;
    @Resource
    GoodsOrderNoteDetailMapper goodsOrderNoteDetailMapper;

    @Resource
    RobOrderMapper robOrderMapper;
    @Resource
    RobOrderNoteMapper robOrderNoteMapper;
    @Resource
    RobOrderNoteDetailMapper robOrderNoteDetailMapper;

    @Resource
    TransitOrderMapper transitOrderMapper;
    @Resource
    TransitOrderNoteMapper transitOrderNoteMapper;
    @Resource
    TransitOrderNoteDetailMapper transitOrderNoteDetailMapper;

    @Resource
    IOrderPaymentCostService orderPaymentCostService;
    @Resource
    IOrderSettlementCostService settlementCostService;
    @Resource
    OrderPaymentCostMapper orderPaymentCostMapper;
    @Resource
    OrderSettlementCostMapper orderSettlementCostMapper;
    @Resource
    IClearingService clearingService;


    @Resource
    IUserRemote userRemote;

    @Override
    public void insertAssignOrderList(List<Map<String, Object>> mapList) {
        Organize plat = ParamUtil.isSuccess(userRemote.getOrganizeById((String) ArrayUtil.first(mapList).get("platId")));
        List<String> errNoList = new ArrayList<>();
        for (int i=0;i< mapList.size();i++) {
            Map<String, Object> map = mapList.get(i);
            if (map.get("shipperOrganizeName").toString().contains("首杨")){
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("-------------------------小镖人数据正在移植，请勿关闭进程--------------------------------");
                logger.info("--------------遇到首杨数据：已跳过----------------");
                logger.info("---------------------------------------------------------------------------------------");
                continue;
            }

            DispatchOrder dispatchOrder = new DispatchOrder();
            dispatchOrder.setId((String) map.get("id"));
//            dispatchOrder.setPlatId((String) map.get("platId"));
//            dispatchOrder.setPlatName(plat.getSuperiorPlatOrganizeId());
//            dispatchOrder.setZonePlatId(plat.getSuperiorPlatOrganizeName());
//            dispatchOrder.setZonePlatName((String) map.get("platName"));
            dispatchOrder.setTitle("派给"+map.get("robOrganizeName")+"的货源");
            dispatchOrder.setDispatchOrderNo((String) map.get("assignOrderNo"));
            dispatchOrder.setDispatchStatus(DispatchOrder.DispatchStatus.going);
            dispatchOrder.setShipperOrganizeId((String) map.get("shipperOrganizeId"));
            dispatchOrder.setShipperOrganizeName((String) map.get("shipperOrganizeName"));
            dispatchOrder.setTruckerOrganizeId((String) map.get("robOrganizeId"));
            dispatchOrder.setTruckerOrganizeName((String) map.get("robOrganizeName"));

            dispatchOrder.setTruckTypeIds((String) map.get("truckTypeIds"));//多个车型逗号隔开
            dispatchOrder.setTruckTypeNames((String) map.get("truckTypeNames"));//多个车型逗号隔开
            dispatchOrder.setTransportTypeId("4028808270f1aeaf0170f1d374170016");
            dispatchOrder.setTransportTypeName("城市配送");
            dispatchOrder.setTransportTypeCode("1003997");

            dispatchOrder.setLimitRobScope(GoodsOrder.LimitRobScope.cooperateScope);
            dispatchOrder.setGoodsRemark((String) map.get("assignRemark"));

            List<Map<String, Object>> goodsConsignorNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsignorNoteListByIds", MapUtil.generate(map1 -> map1.put("ids", map.get("consignorNoteIds"))));
            List<Map<String, Object>> goodsConsigneeNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsigneeNoteListByIds", MapUtil.generate(map1 -> map1.put("ids", map.get("consigneeNoteIds"))));

            List<DispatchOrderNote> dispatchOrderNoteList = new ArrayList<>();
            double glassW = 0;
            for (Map<String, Object> orMap : goodsConsignorNoteList) {
                for (Map<String, Object> eeMap : goodsConsigneeNoteList) {
                    List<Map<String, Object>> goodsNoteDetailList = AppUtil.migrationListPost("/order/migration/getGoodsNoteDetailList", MapUtil.generate(map12 -> {
                        map12.put("goodsConsignorNoteId", orMap.get("id"));
                        map12.put("goodsConsigneeNoteId", eeMap.get("id"));
                    }));
                    if (goodsNoteDetailList.size() > 0) {
                        DispatchOrderNote disOrderNote = new DispatchOrderNote();
//                        disOrderNote.setPlatId(dispatchOrder.getPlatId());
//                        disOrderNote.setPlatName(dispatchOrder.getPlatName());
//                        disOrderNote.setZonePlatId(dispatchOrder.getZonePlatId());
//                        disOrderNote.setZonePlatName(dispatchOrder.getZonePlatName());
                        disOrderNote.setConsignorArea((String) orMap.get("consignorArea"));
                        disOrderNote.setConsignorName((String) orMap.get("consignorName"));
                        disOrderNote.setConsignorPhone((String) orMap.get("consignorPhone"));
                        disOrderNote.setConsignorCoordinate((String) orMap.get("consignorCoordinate"));
                        disOrderNote.setConsignorAddress((String) orMap.get("consignorAddress"));
                        disOrderNote.setConsignorAdCode((String) orMap.get("consignorAdCode"));

                        disOrderNote.setConsigneeArea((String) eeMap.get("consigneeArea"));
                        disOrderNote.setConsigneeName((String) eeMap.get("consigneeName"));
                        disOrderNote.setConsigneePhone((String) eeMap.get("consigneePhone"));
                        disOrderNote.setConsigneeCoordinate((String) eeMap.get("consigneeCoordinate"));
                        disOrderNote.setConsigneeAddress((String) eeMap.get("consigneeAddress"));
                        disOrderNote.setConsigneeAdCode((String) eeMap.get("consigneeAdCode"));

                        disOrderNote.setDispatchOrderId(dispatchOrder.getId());
                        disOrderNote.setGoodsNoteMeasure(ArrayUtil.numListAdd(goodsNoteDetailList, obj -> (Double) obj.get("goodsMeasure")));
                        disOrderNote.setGoodsNoteTransportCost(ArrayUtil.numListAdd(goodsNoteDetailList, obj -> (Double) obj.get("goodsTransportCost")));
                        disOrderNote.setMeasureUnit((String) ArrayUtil.first(goodsNoteDetailList).get("measureUnit"));
                        dispatchOrderNoteMapper.insert(disOrderNote);
                        dispatchOrderNoteList.add(disOrderNote);

                        List<DispatchOrderNoteDetail> list = JsonUtil.jsonToObject(JsonUtil.objectToJson(goodsNoteDetailList), new TypeToken<List<DispatchOrderNoteDetail>>() {});
                        for (DispatchOrderNoteDetail dispatchOrderNoteDetail : list) {
                            dispatchOrderNoteDetail.setDispatchOrderId(dispatchOrder.getId());
                            dispatchOrderNoteDetail.setDispatchOrderNoteId(disOrderNote.getId());
                            dispatchOrderNoteDetailMapper.insert(dispatchOrderNoteDetail);
                            glassW += dispatchOrderNoteDetail.getGrossWeight();
                        }
                    }
                }
            }

//            dispatchOrder.setKilometer((Double) map.get(""));//总距离 单位：km
//            dispatchOrder.setDuration((Integer) map.get("")); //预计时间 单位：秒
//            dispatchOrder.setGoodsTypeName((String) map.get("")); //货物类型显示（用于在列表显示，货物列表第一个）
            if (dispatchOrderNoteList.isEmpty()){
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("-------------------------小镖人数据正在移植，请勿关闭进程--------------------------------");
                logger.info("--------------找不到货物信息，已跳过"+dispatchOrder.getDispatchOrderNo()+"----------------");
                logger.info("---------------------------------------------------------------------------------------");
                errNoList.add(dispatchOrder.getDispatchOrderNo());
                continue;
            }

            dispatchOrder.setShipperTotalMeasure(ArrayUtil.numListAdd(dispatchOrderNoteList, DispatchOrderNote::getGoodsNoteMeasure));
            dispatchOrder.setMeasureUnit(ArrayUtil.first(dispatchOrderNoteList).getMeasureUnit());//修改：单位放在货源，统一计量单位
            dispatchOrder.setTotalGrossWeight(glassW);

            dispatchOrder.setPriceMode(GoodsOrder.PriceMode.notPrice);//
            dispatchOrder.setSettlementType(GoodsOrder.SettlementType.gatherTotal);
            dispatchOrder.setShipperTransportCost((Double) map.get("shipperTransportCost"));//主费用: 司机运输费【前台显示】
            dispatchOrder.setShipperAdditionalCost(0d);//3.装卸费等
            dispatchOrder.setShipperAdditionalDetails("");
            dispatchOrder.setInsuredAmount(0d);

            dispatchOrder.setFullLoad((Boolean) map.get("fullLoad"));
            dispatchOrder.setMatching((Boolean) map.get("matching"));
            dispatchOrder.setIncludedTax ((Boolean) map.get("includedTax"));
            dispatchOrder.setNoBargain (true);
            dispatchOrder.setAutoAudit ((Boolean) map.get("autoAudit"));
            dispatchOrder.setStartFence((Boolean) map.get("startFence"));
            dispatchOrder.setNeedUploadShipping((Boolean) map.get("needUploadShipping"));
            dispatchOrder.setAutoDelivery((Boolean) map.get("autoDelivery"));
            dispatchOrder.setNeedUploadReceipt((Boolean) map.get("needUploadReceipt"));
            dispatchOrder.setSkipConfirmReceipt ((Boolean) map.get("skipConfirmReceipt"));
            dispatchOrder.setHandLiquidation((Boolean) map.get("handLiquidation"));
            dispatchOrderMapper.insert(dispatchOrder);

            logger.info("---------------------------------------------------------------------------------------");
            logger.info("-------------------------小镖人数据正在移植，请勿关闭进程--------------------------------");
            logger.info(String.format("--------------派单移植进度（%s/%s）:%s----------------",i+1,mapList.size(),dispatchOrder.getDispatchOrderNo()));
            logger.info("---------------------------------------------------------------------------------------");
        }
        logger.info("---------------------------------------------------------------------------------------");
        logger.info(String.format("----------派单移植完成，错误跳过的抢单号：%s-------------",String.join(",",errNoList)));
        logger.info("---------------------------------------------------------------------------------------");
    }

    @Override
    public void insertGoodsOrderList(List<Map<String, Object>> mapList) {
        for (int i=0;i< mapList.size();i++) {
            Map<String, Object> map = mapList.get(i);
            GoodsOrder goodsOrder = JsonUtil.mapToObject(map, new TypeToken<GoodsOrder>() {});
            MemberType memberType = ParamUtil.isSuccess(userRemote.getMyMemberTypeByOrganizeId(goodsOrder.getShipperOrganizeId()));
            goodsOrder.setReleasePaymentRate(memberType.getReleasePaymentRate());
            goodsOrder.setRobPaymentRate(memberType.getRobPaymentRate());
            goodsOrder.setDeliverPaymentRate(memberType.getDeliverPaymentRate());
            goodsOrder.setArrivalPaymentRate(memberType.getArrivalPaymentRate());
            goodsOrder.setShipperFeeRate(memberType.getShipperCarrierFeeRate());
            goodsOrder.setShipperTaxRate(memberType.getOwnerTaxRate());
            goodsOrder.setInsuranceRate(memberType.getInsuranceRate());

            goodsOrder.setDisplayConsignorArea((String) map.get("consignorArea"));
            goodsOrder.setDisplayConsignorCoordinate((String) map.get("consignorCoordinate"));
            goodsOrder.setDisplayConsigneeArea((String) map.get("consigneeArea"));
            goodsOrder.setDisplayConsigneeCoordinate((String) map.get("consigneeCoordinate"));
            goodsOrderMapper.insert(goodsOrder);
            //获取发货点和收货点
            List<Map<String, Object>> goodsConsignorNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsignorNoteList", MapUtil.generate(map1 -> map1.put("goodsOrderId", goodsOrder.getId())));
            List<Map<String, Object>> goodsConsigneeNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsigneeNoteList", MapUtil.generate(map1 -> map1.put("goodsOrderId", goodsOrder.getId())));

            for (Map<String, Object> orMap : goodsConsignorNoteList) {
                for (Map<String, Object> eeMap : goodsConsigneeNoteList) {
                    List<Map<String, Object>> goodsNoteDetailList = AppUtil.migrationListPost("/order/migration/getGoodsNoteDetailList", MapUtil.generate(map12 -> {
                        map12.put("goodsConsignorNoteId", orMap.get("id"));
                        map12.put("goodsConsigneeNoteId", eeMap.get("id"));
                    }));
                    if (goodsNoteDetailList.size() > 0) {
                        GoodsOrderNote goodsOrderNote = new GoodsOrderNote();
//                        goodsOrderNote.setPlatId(goodsOrder.getPlatId());
//                        goodsOrderNote.setPlatName(goodsOrder.getPlatName());
//                        goodsOrderNote.setZonePlatId(goodsOrder.getZonePlatId());
//                        goodsOrderNote.setZonePlatName(goodsOrder.getZonePlatName());
                        goodsOrderNote.setConsignorArea((String) orMap.get("consignorArea"));
                        goodsOrderNote.setConsignorName((String) orMap.get("consignorName"));
                        goodsOrderNote.setConsignorPhone((String) orMap.get("consignorPhone"));
                        goodsOrderNote.setConsignorCoordinate((String) orMap.get("consignorCoordinate"));
                        goodsOrderNote.setConsignorAddress((String) orMap.get("consignorAddress"));
                        goodsOrderNote.setConsignorAdCode((String) orMap.get("consignorAdCode"));

                        goodsOrderNote.setConsigneeArea((String) eeMap.get("consigneeArea"));
                        goodsOrderNote.setConsigneeName((String) eeMap.get("consigneeName"));
                        goodsOrderNote.setConsigneePhone((String) eeMap.get("consigneePhone"));
                        goodsOrderNote.setConsigneeCoordinate((String) eeMap.get("consigneeCoordinate"));
                        goodsOrderNote.setConsigneeAddress((String) eeMap.get("consigneeAddress"));
                        goodsOrderNote.setConsigneeAdCode((String) eeMap.get("consigneeAdCode"));

                        goodsOrderNote.setGoodsOrderId(goodsOrder.getId());
                        goodsOrderNote.setGoodsNoteMeasure(ArrayUtil.numListAdd(goodsNoteDetailList, obj -> (Double) obj.get("goodsMeasure")));
                        goodsOrderNote.setGoodsNoteTransportCost(ArrayUtil.numListAdd(goodsNoteDetailList, obj -> (Double) obj.get("goodsTransportCost")));
                        goodsOrderNote.setGoodsNoteEmbarkMeasure(ArrayUtil.numListAdd(goodsNoteDetailList, obj -> (Double) obj.get("embarkMeasure")));
                        goodsOrderNote.setMeasureUnit(goodsOrder.getMeasureUnit());
                        goodsOrderNoteMapper.insert(goodsOrderNote);

                        List<GoodsOrderNoteDetail> list = JsonUtil.jsonToObject(JsonUtil.objectToJson(goodsNoteDetailList), new TypeToken<List<GoodsOrderNoteDetail>>() {});
                        for (GoodsOrderNoteDetail goodsOrderNoteDetail : list) {
                            goodsOrderNoteDetail.setGoodsOrderNoteId(goodsOrderNote.getId());
                            goodsOrderNoteDetail.setGoodsOrderId(goodsOrder.getId());
                            goodsOrderNoteDetailMapper.insert(goodsOrderNoteDetail);
                        }
                    }
                }
            }
            ///生成发布支付单
            if (goodsOrder.getPriceMode() == GoodsOrder.PriceMode.notPrice) {
                orderPaymentCostService.generateGoodsOrderPayment(goodsOrder);
            }
            logger.info("---------------------------------------------------------------------------------------");
            logger.info("-------------------------小镖人数据正在移植，请勿关闭进程--------------------------------");
            logger.info(String.format("--------------货源移植进度（%s/%s）:%s----------------",i+1,mapList.size(),goodsOrder.getGoodsOrderNo()));
            logger.info("---------------------------------------------------------------------------------------");
        }
    }

    @Override
    public void insertRobOrderList(List<Map<String, Object>> mapList) {
        List<String> errNoList = new ArrayList<>();
        List<String> extNoList = new ArrayList<>();
        for (int i=0;i< mapList.size();i++) {
            Map<String, Object> map = mapList.get(i);
            RobOrder robOrder = JsonUtil.mapToObject(map, new TypeToken<RobOrder>() {});
            RobOrder localRobOrder = robOrderMapper.selectById(robOrder.getId());
            if (localRobOrder!=null) {
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("---------------------抢单已存在，移植已跳过-----------------------------");
                logger.info(String.format("----------抢单跳过（%s/%s）:%s-------------",i+1,mapList.size(),robOrder.getRobOrderNo()));
                logger.info("---------------------------------------------------------------------------------------");
                extNoList.add(robOrder.getRobOrderNo());
                continue;
            }
            GoodsOrder goodsOrder = goodsOrderMapper.selectById(robOrder.getGoodsOrderId());
            if (goodsOrder==null) {
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("---------------------抢单移植时因为找不到对应货单，移植已跳过-----------------------------");
                logger.info(String.format("----------异常抢单跳过（%s/%s）:%s-------------",i+1,mapList.size(),robOrder.getRobOrderNo()));
                logger.info("---------------------------------------------------------------------------------------");
                errNoList.add(robOrder.getRobOrderNo());
                continue;
            }
            MemberType memberType = ParamUtil.isSuccess(userRemote.getMyMemberTypeByOrganizeId(robOrder.getRobOrganizeId()));
            if (memberType==null){
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("---------------------抢单移植时因为找不到抢单组织，移植已跳过-----------------------------");
                logger.info(String.format("----------异常抢单跳过（%s/%s）:%s-------------",i+1,mapList.size(),robOrder.getRobOrderNo()));
                logger.info("---------------------------------------------------------------------------------------");
                errNoList.add(robOrder.getRobOrderNo());
                continue;
            }
            robOrder.setTruckerFeeRate(robOrder.getMatching() ? memberType.getTruckerMatchFeeRate() : memberType.getTruckerCarrierFeeRate());
            robOrder.setAddedTaxRate(memberType.getAddedTaxRate());
            robOrder.setCityTaxRate(memberType.getCityTaxRate());
            robOrder.setLocalEduTaxRate(memberType.getLocalEduTaxRate());
            robOrder.setEduAddTaxRate(memberType.getEduAddTaxRate());
            robOrder.setIncomeTaxRate(memberType.getIncomeTaxRate());
            robOrder.setDisplayConsignorArea((String) map.get("consignorArea"));
            robOrder.setDisplayConsignorCoordinate((String) map.get("consignorCoordinate"));
            robOrder.setDisplayConsigneeArea((String) map.get("consigneeArea"));
            robOrder.setDisplayConsigneeCoordinate((String) map.get("consigneeCoordinate"));
            robOrderMapper.insert(robOrder);
            //获取发货点和收货点
            List<Map<String, Object>> goodsConsignorNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsignorNoteList", MapUtil.generate(map1 -> map1.put("goodsOrderId", robOrder.getGoodsOrderId())));
            List<Map<String, Object>> goodsConsigneeNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsigneeNoteList", MapUtil.generate(map1 -> map1.put("goodsOrderId", robOrder.getGoodsOrderId())));

            for (Map<String, Object> orMap : goodsConsignorNoteList) {
                for (Map<String, Object> eeMap : goodsConsigneeNoteList) {
                    List<Map<String, Object>> robNoteDetailList = AppUtil.migrationListPost("/order/migration/getRobNoteDetailList", MapUtil.generate(map12 -> {
                        map12.put("robOrderId", robOrder.getId());
                        map12.put("goodsConsignorNoteId", orMap.get("id"));
                        map12.put("goodsConsigneeNoteId", eeMap.get("id"));
                    }));
                    if (robNoteDetailList.size() > 0) {
                        RobOrderNote robOrderNote = new RobOrderNote();
//                        robOrderNote.setPlatId(robOrder.getPlatId());
//                        robOrderNote.setPlatName(robOrder.getPlatName());
//                        robOrderNote.setZonePlatId(robOrder.getZonePlatId());
//                        robOrderNote.setZonePlatName(robOrder.getZonePlatName());
                        robOrderNote.setConsignorArea((String) orMap.get("consignorArea"));
                        robOrderNote.setConsignorName((String) orMap.get("consignorName"));
                        robOrderNote.setConsignorPhone((String) orMap.get("consignorPhone"));
                        robOrderNote.setConsignorCoordinate((String) orMap.get("consignorCoordinate"));
                        robOrderNote.setConsignorAddress((String) orMap.get("consignorAddress"));
                        robOrderNote.setConsignorAdCode((String) orMap.get("consignorAdCode"));

                        robOrderNote.setConsigneeArea((String) eeMap.get("consigneeArea"));
                        robOrderNote.setConsigneeName((String) eeMap.get("consigneeName"));
                        robOrderNote.setConsigneePhone((String) eeMap.get("consigneePhone"));
                        robOrderNote.setConsigneeCoordinate((String) eeMap.get("consigneeCoordinate"));
                        robOrderNote.setConsigneeAddress((String) eeMap.get("consigneeAddress"));
                        robOrderNote.setConsigneeAdCode((String) eeMap.get("consigneeAdCode"));

                        robOrderNote.setGoodsOrderId(robOrder.getGoodsOrderId());
                        robOrderNote.setRobOrderId(robOrder.getId());
                        robOrderNote.setRobNoteMeasure(ArrayUtil.numListAdd(robNoteDetailList, obj -> (Double) obj.get("robMeasure")));
                        robOrderNote.setRobNoteTransportCost(ArrayUtil.numListAdd(robNoteDetailList, obj -> (Double) obj.get("robTransportCost")));
                        robOrderNote.setMeasureUnit(robOrder.getMeasureUnit());
                        robOrderNoteMapper.insert(robOrderNote);

                        for (Map<String, Object> stringObjectMap : robNoteDetailList) {
                            stringObjectMap.put("goodsOrderNoteDetailId",stringObjectMap.get("goodsNoteDetailId"));
                        }
                        List<RobOrderNoteDetail> list = JsonUtil.jsonToObject(JsonUtil.objectToJson(robNoteDetailList), new TypeToken<List<RobOrderNoteDetail>>() {
                        });
                        for (RobOrderNoteDetail robOrderNoteDetail : list) {
                            robOrderNoteDetail.setRobOrderNoteId(robOrderNote.getId());
                            robOrderNoteDetail.setGoodsOrderId(robOrder.getGoodsOrderId());
                            robOrderNoteDetail.setRobOrderId(robOrder.getId());
                            robOrderNoteDetailMapper.insert(robOrderNoteDetail);
                        }
                    }
                }
            }

            ///生成抢单支付单
            if (robOrder.getPriceMode() == GoodsOrder.PriceMode.notPrice) {
                orderPaymentCostService.generateRobOrderPayment(robOrder, goodsOrder);
            }
            logger.info("---------------------------------------------------------------------------------------");
            logger.info("-------------------------小镖人数据正在移植，请勿关闭进程--------------------------------");
            logger.info(String.format("----------抢单移植进度（%s/%s）:%s-------------",i+1,mapList.size(),robOrder.getRobOrderNo()));
            logger.info("---------------------------------------------------------------------------------------");
        }
        logger.info("---------------------------------------------------------------------------------------");
        logger.info(String.format("----------抢单移植完成，已存在跳过的抢单号：%s-------------",String.join(",",extNoList)));
        logger.info("---------------------------------------------------------------------------------------");
        logger.info(String.format("----------抢单移植完成，错误跳过的抢单号：%s-------------",String.join(",",errNoList)));
        logger.info("---------------------------------------------------------------------------------------");
    }

    @Override
    public void insertTransitOrderList(int page, List<Map<String, Object>> mapList) {
        List<String> errNoList = new ArrayList<>();
        List<String> extNoList = new ArrayList<>();
        for (int i=0;i< mapList.size();i++) {
            Map<String, Object> map = mapList.get(i);
            TransitOrder transitOrder = JsonUtil.mapToObject(map, new TypeToken<TransitOrder>() {});
            TransitOrder localTransitOrder = transitOrderMapper.selectById(transitOrder.getId());
            if (localTransitOrder!=null) {
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("---------------------运单已存在，移植已跳过-----------------------------");
                logger.info(String.format("----------运单跳过（%s/%s）:%s-------------",i+1,mapList.size(),transitOrder.getRobOrderNo()));
                logger.info("---------------------------------------------------------------------------------------");
                extNoList.add(transitOrder.getTransportNo());
                continue;
            }
            GoodsOrder goodsOrder = goodsOrderMapper.selectById(transitOrder.getGoodsOrderId());
            if (goodsOrder==null) {
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("---------------------运单移植时因为找不到对应货单，移植已跳过-----------------------------");
                logger.info(String.format("----------异常运单跳过（%s/%s）:%s-------------",i+1,mapList.size(),transitOrder.getTransportNo()));
                logger.info("---------------------------------------------------------------------------------------");
                errNoList.add(transitOrder.getTransportNo());
                continue;
            }
            RobOrder robOrder = robOrderMapper.selectById(transitOrder.getRobOrderId());
            if (robOrder==null) {
                logger.info("---------------------------------------------------------------------------------------");
                logger.info("---------------------运单移植时因为找不到对应抢单，移植已跳过-----------------------------");
                logger.info(String.format("----------异常运单跳过（%s/%s）:%s-------------",i+1,mapList.size(),transitOrder.getTransportNo()));
                logger.info("---------------------------------------------------------------------------------------");
                errNoList.add(transitOrder.getTransportNo());
                continue;
            }
            transitOrder.setDisplayConsignorArea((String) map.get("consignorArea"));
            transitOrder.setDisplayConsignorCoordinate((String) map.get("consignorCoordinate"));
            transitOrder.setDisplayConsigneeArea((String) map.get("consigneeArea"));
            transitOrder.setDisplayConsigneeCoordinate((String) map.get("consigneeCoordinate"));
            //获取发货点和收货点
            List<Map<String, Object>> goodsConsignorNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsignorNoteList", MapUtil.generate(map1 -> map1.put("goodsOrderId", transitOrder.getGoodsOrderId())));
            List<Map<String, Object>> goodsConsigneeNoteList = AppUtil.migrationListPost("/order/migration/getGoodsConsigneeNoteList", MapUtil.generate(map1 -> map1.put("goodsOrderId", transitOrder.getGoodsOrderId())));

            for (Map<String, Object> orMap : goodsConsignorNoteList) {
                for (Map<String, Object> eeMap : goodsConsigneeNoteList) {
                    List<Map<String, Object>> transitNoteDetailList = AppUtil.migrationListPost("/order/migration/getTransitNoteDetailList", MapUtil.generate(map12 -> {
                        map12.put("transitOrderId", transitOrder.getId());
                        map12.put("goodsConsignorNoteId", orMap.get("id"));
                        map12.put("goodsConsigneeNoteId", eeMap.get("id"));
                    }));
                    if (transitNoteDetailList.size() > 0) {
                        TransitOrderNote transitOrderNote = new TransitOrderNote();
//                        transitOrderNote.setPlatId(transitOrder.getPlatId());
//                        transitOrderNote.setPlatName(transitOrder.getPlatName());
//                        transitOrderNote.setZonePlatId(transitOrder.getZonePlatId());
//                        transitOrderNote.setZonePlatName(transitOrder.getZonePlatName());
                        transitOrderNote.setConsignorArea((String) orMap.get("consignorArea"));
                        transitOrderNote.setConsignorName((String) orMap.get("consignorName"));
                        transitOrderNote.setConsignorPhone((String) orMap.get("consignorPhone"));
                        transitOrderNote.setConsignorCoordinate((String) orMap.get("consignorCoordinate"));
                        transitOrderNote.setConsignorAddress((String) orMap.get("consignorAddress"));
                        transitOrderNote.setConsignorAdCode((String) orMap.get("consignorAdCode"));

                        transitOrderNote.setConsigneeArea((String) eeMap.get("consigneeArea"));
                        transitOrderNote.setConsigneeName((String) eeMap.get("consigneeName"));
                        transitOrderNote.setConsigneePhone((String) eeMap.get("consigneePhone"));
                        transitOrderNote.setConsigneeCoordinate((String) eeMap.get("consigneeCoordinate"));
                        transitOrderNote.setConsigneeAddress((String) eeMap.get("consigneeAddress"));
                        transitOrderNote.setConsigneeAdCode((String) eeMap.get("consigneeAdCode"));

                        transitOrderNote.setGoodsOrderId(transitOrder.getGoodsOrderId());
                        transitOrderNote.setRobOrderId(transitOrder.getRobOrderId());
                        transitOrderNote.setTransitOrderId(transitOrder.getId());
                        transitOrderNote.setNoteAssignMeasure(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("assignMeasure")));
                        transitOrderNote.setNoteAssignTransportCost(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("assignTransportCost")));
                        transitOrderNote.setNoteAssignTime(DateTimeUtil.stringToDate((String) ArrayUtil.first(transitNoteDetailList).get("assignTime"), null));

                        transitOrderNote.setNoteLoadingMeasure(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("loadingMeasure")));
                        transitOrderNote.setNoteLoadingTransportCost(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("loadingTransportCost")));
                        transitOrderNote.setNoteLoadingTime(DateTimeUtil.stringToDate((String) ArrayUtil.first(transitNoteDetailList).get("loadingTime"), null));

                        transitOrderNote.setNoteDeliverMeasure(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("deliverMeasure")));
                        transitOrderNote.setNoteDeliverTransportCost(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("deliverTransportCost")));
                        transitOrderNote.setNoteDeliverTime(DateTimeUtil.stringToDate((String) ArrayUtil.first(transitNoteDetailList).get("deliverTime"), null));

                        transitOrderNote.setNoteReceiptMeasure(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("receiptMeasure")));
                        transitOrderNote.setNoteReceiptTransportCost(ArrayUtil.numListAdd(transitNoteDetailList, obj -> (Double) obj.get("receiptTransportCost")));
                        transitOrderNote.setNoteReceiptTime(DateTimeUtil.stringToDate((String) ArrayUtil.first(transitNoteDetailList).get("receiptTime"), null));

                        transitOrderNote.setMeasureUnit(transitOrder.getMeasureUnit());
                        if (transitOrder.getTransitStatus().index >= TransitOrder.TransitStatus.waitingReceipt.index) {
                            transitOrderNote.setNoteStatus(TransitOrderNote.NoteStatus.transitEnd);
                        } else if (transitOrder.getTransitStatus().index >= TransitOrder.TransitStatus.waitingArrive.index) {
                            transitOrderNote.setNoteStatus(TransitOrderNote.NoteStatus.waitReceipt);
                        } else if (transitOrder.getTransitStatus().index >= TransitOrder.TransitStatus.waitingDelivery.index) {
                            transitOrderNote.setNoteStatus(TransitOrderNote.NoteStatus.waitDeliver);
                        } else if (transitOrder.getTransitStatus().index >= TransitOrder.TransitStatus.waitingLoading.index) {
                            transitOrderNote.setNoteStatus(TransitOrderNote.NoteStatus.waitLoading);
                        }
                        transitOrderNote.setNoteStatus(TransitOrderNote.NoteStatus.waitLoading);
                        transitOrderNoteMapper.insert(transitOrderNote);
                        for (Map<String, Object> stringObjectMap : transitNoteDetailList) {
                            stringObjectMap.put("goodsOrderNoteDetailId",stringObjectMap.get("goodsNoteDetailId"));
                            stringObjectMap.put("robOrderNoteDetailId",stringObjectMap.get("robNoteDetailId"));
                        }
                        List<TransitOrderNoteDetail> list = JsonUtil.jsonToObject(JsonUtil.objectToJson(transitNoteDetailList), new TypeToken<List<TransitOrderNoteDetail>>() {
                        });
                        for (TransitOrderNoteDetail transitOrderNoteDetail : list) {
                            transitOrderNoteDetail.setTransitOrderNoteId(transitOrderNote.getId());
                            transitOrderNoteDetail.setGoodsOrderId(transitOrderNote.getGoodsOrderId());
                            transitOrderNoteDetail.setRobOrderId(transitOrderNote.getRobOrderId());
                            transitOrderNoteDetail.setTransitOrderId(transitOrder.getId());
                            transitOrderNoteDetailMapper.insert(transitOrderNoteDetail);
                        }
                    }
                }
            }
            List<TransitOrderNote> goodsOrderNoteList = transitOrderNoteMapper.selectList(new QueryWrapper<TransitOrderNote>().eq("transit_order_id", transitOrder.getId()));
            transitOrder.setPlanningConsignorNoteId(ArrayUtil.first(goodsOrderNoteList).getId());
            transitOrder.setPlanningConsignorName(ArrayUtil.first(goodsOrderNoteList).getConsignorName());
            transitOrder.setPlanningConsignorCoordinate(ArrayUtil.first(goodsOrderNoteList).getConsignorCoordinate());
            transitOrder.setPlanningConsignorAddress(ArrayUtil.first(goodsOrderNoteList).getConsignorAddress());
            transitOrder.setPlanningConsignorAdCode(ArrayUtil.first(goodsOrderNoteList).getConsignorAdCode());
            transitOrder.setPlanningConsigneeNoteId(ArrayUtil.last(goodsOrderNoteList).getId());
            transitOrder.setPlanningConsigneeName(ArrayUtil.last(goodsOrderNoteList).getConsigneeName());
            transitOrder.setPlanningConsigneeCoordinate(ArrayUtil.last(goodsOrderNoteList).getConsigneeCoordinate());
            transitOrder.setPlanningConsigneeAddress(ArrayUtil.last(goodsOrderNoteList).getConsigneeAddress());
            transitOrder.setPlanningConsigneeAdCode(ArrayUtil.last(goodsOrderNoteList).getConsigneeAdCode());
            transitOrderMapper.insert(transitOrder);
            ///生成支付单
            if (transitOrder.getPriceMode() == GoodsOrder.PriceMode.notPrice) {
                if (transitOrder.getTransitStatus().index > TransitOrder.TransitStatus.waitingDelivery.index) {
                    orderPaymentCostService.generateDeliveryOrderPayment(transitOrder, robOrder);
                }
                if (transitOrder.getTransitStatus().index > TransitOrder.TransitStatus.waitingReceipt.index) {
                    orderPaymentCostService.generateReceiptOrderPayment(transitOrder);
                }
                if (transitOrder.getTransitStatus().index > TransitOrder.TransitStatus.waitingSettlement.index) {
                    //生成清算单
                    ClearingDetail clearingDetail = clearingService.createClearingDetail(transitOrder);
                    OrderPaymentCost orderPaymentCost = orderPaymentCostService.generateClearingOrderPayment(transitOrder, clearingDetail);
                    //生成平台 > 司机结算单
                    OrderSettlementCost orderSettlementCost = settlementCostService.generateOrderSettlement(transitOrder, clearingDetail);
                    //-----------------------------------------------------------------------------------
                    //更新运单--完成
                    transitOrder.setClearingDetailId(clearingDetail.getId());
                    transitOrder.setClearCompleteTime(new Date());
                    transitOrder.setShipperActualPayCost(clearingDetail.getShipperActualPayCost());
                    transitOrder.setTruckerActualIncomeCost(clearingDetail.getTruckerActualIncomeCost());
                    transitOrder.setTransitStatus(TransitOrder.TransitStatus.complete);
                    transitOrderMapper.updateById(transitOrder);

                    if (transitOrder.getTransitStatus()== TransitOrder.TransitStatus.complete){
                        clearingDetail.setOptTime(new Date());
                        clearingDetail.setClearingStatus(ClearingDetail.ClearingStatus.success);
                        //-----------------------------------------------------------------------------------
                        clearingService.updateById(clearingDetail);
                        //更新运单--完成
                        transitOrder.setClearingDetailId(clearingDetail.getId());
                        transitOrder.setClearCompleteTime(new Date());
                        transitOrder.setShipperActualPayCost(clearingDetail.getShipperActualPayCost());
                        transitOrder.setTruckerActualIncomeCost(clearingDetail.getTruckerActualIncomeCost());
                        transitOrderMapper.updateById(transitOrder);

                        orderPaymentCost.setPayStatus(OrderPaymentCost.PayStatus.complete);
                        orderPaymentCost.setPayRemark("在V4.5.0(2023年9月15日前)之前的运单暂时无法追溯交易记录，若必须查看，请联系开发人员！");
                        orderPaymentCostMapper.updateById(orderPaymentCost);

                        orderSettlementCost.setPayStatus(OrderSettlementCost.PayStatus.success);
                        orderSettlementCost.setPayRemark("在V4.5.0(2023年9月15日前)之前的运单暂时无法追溯交易记录，若必须查看，请联系开发人员！");
                        orderSettlementCostMapper.updateById(orderSettlementCost);
                    }
                }
            }
            logger.info("---------------------------------------------------------------------------------------");
            logger.info("-------------------------小镖人数据正在移植，请勿关闭进程--------------------------------");
            logger.info(String.format("--------------运单移植进度（%s:%s/%s）:%s--------------",page,i+1,mapList.size(),transitOrder.getTransportNo()));
            logger.info("---------------------------------------------------------------------------------------");
        }
        logger.info("---------------------------------------------------------------------------------------");
        logger.info(String.format("----------运单移植完成，已存在跳过的运单号：%s-------------",String.join(",",extNoList)));
        logger.info("---------------------------------------------------------------------------------------");
        logger.info(String.format("----------运单移植完成，错误跳过的运单号：%s-------------",String.join(",",errNoList)));
        logger.info("---------------------------------------------------------------------------------------");
    }
}
